﻿#region Copyright (C) Sector7 Software Studio. All rights reserved
/*******************************************************************************************
 * Creation
 *      Author:         Wolf Lai
 *      Date:           2011/10/27 22:06:14
 *      Version:        1.0.1101
 * Modification 
 *      Author: 
 *      Date: 
 *      Description: 
 *      Version:
 *******************************************************************************************/
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Win32;
using Sector7.Framework.Enums;
using Sector7.Framework.Core;
using Sector7.Framework.Consts;

namespace Sector7.Framework.Utility
{
    /// <summary>
    /// 注册表读写工具类
    /// </summary>
    public class RegistryUtil
    {
        #region Public functions
        /// <summary>
        /// 获取指定子键属性值
        /// </summary>
        /// <param name="mainKey">注册表主键类型</param>
        /// <param name="subKeyName">要打开的子项名称或路径</param>
        /// <param name="propertyName">属性名</param>
        /// <returns></returns>
        /// <exception cref="Exception">未查询到指定子键，则抛出Exception异常</exception>
        public static string GetPropertyValue(RegistryKey mainKey, string subKeyName, string propertyName)
        {
            RegistryKey subKey = mainKey.OpenSubKey(subKeyName);

            if (subKey != null)
            {
                object value = subKey.GetValue(propertyName);

                if (value != null)
                    return value.ToString();
            }

            throw new KeyNotFoundException("Assigned rgistry key not found.");
        }

        /// <summary>
        /// 获取指定子键属性字典
        /// </summary>
        /// <param name="mainKey">注册表主键类型</param>
        /// <param name="subKeyName">要打开的子项名称或路径</param>
        /// <returns></returns>
        public static Dictionary<string, string> GetProperties(RegistryKey mainKey, string subKeyName)
        {
            Dictionary<string, string> properties = new Dictionary<string, string>();

            try
            {
                RegistryKey subKey = mainKey.OpenSubKey(subKeyName);

                string[] propertyNames = subKey.GetValueNames();
                object propertyValue;

                foreach (string propertyName in propertyNames)
                {
                    propertyValue = subKey.GetValue(propertyName);

                    if (propertyValue != null)
                        properties.Add(propertyName, propertyValue.ToString());
                }
            }
            catch (Exception e)
            {
                Log.WriteLine(LogSeverityType.WRN, C_ModuleName.FRAMEWORK, e);
                properties.Clear();
            }

            return properties;
        }
        #endregion
    }
}
